package com.ygqh.baby.controller.mobile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.ygqh.baby.interceptor.YgExceptionHandler;

public class BaseController extends YgExceptionHandler {
	protected Logger logger = Logger.getLogger(this.getClass());

	protected final BigDecimal zero = new BigDecimal("0.00");

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); // true:允许输入空值，false:不能为空值
	}
	protected   String getRequestPostStr(HttpServletRequest request){
        try {
			byte buffer[] = getRequestPostBytes(request);
			String charEncoding = request.getCharacterEncoding();
			if (charEncoding == null) {
			    charEncoding = "UTF-8";
			}
			return new String(buffer, charEncoding);
		} catch (IOException e) {
			e.printStackTrace();
		}
        return "";
    }

	protected  byte[] getRequestPostBytes(HttpServletRequest request)
	        throws IOException {
	    int contentLength = request.getContentLength();
	    if(contentLength<0){
	        return null;	
	    }
	    byte buffer[] = new byte[contentLength];
	    for (int i = 0; i < contentLength;) {
	
	        int readlen = request.getInputStream().read(buffer, i,
	                contentLength - i);
	        if (readlen == -1) {
	            break;
	        }
	        i += readlen;
	    }
	    return buffer;
	}

	public Map<String, String> getParameterMap(Map<String, String[]> requestParams) {
		Map<String, String> params = new HashMap<String, String>();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			/*
			 * valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
			 */
			params.put(name, valueStr);
		}
		return params;
	}
}
